package com.example.demo.demos.web;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {

        List<Integer> ageList = Arrays.asList(20, 25, 30);

        List<String> nameList = Arrays.asList("阿三", "毕四", "曹五");

        List<User> userList = Arrays.asList(
                User.builder().name("阿三").age(20).build(),
                User.builder().name("毕四").age(25).build(),
                User.builder().name("曹五").age(30).build()
        );

        Map<String, List<User>> groupMap = userList.stream()
                .collect(Collectors.groupingBy(u -> u.getName() + "|" + u.getAge()));


        Map<String, List<User>> map = groupingBy(userList, User::getName, User::getAge);


        map.forEach((k, v) -> {
            System.out.println(k);
            System.out.println(v);
        });
    }


    /**
     * 将数据分组，根据方法引用（bean的get方法）
     *
     * @param list      为分组的数据
     * @param functions get方法数组
     */
    @SafeVarargs
    public static <T, R> Map<String, List<T>> groupingBy(List<T> list, Function<T, R>... functions) {
        return list.stream().collect(Collectors.groupingBy(t -> groupingBy(t, functions)));
    }

    /**
     * 分组工具根据函数式接口使用分组，将数据根据分组结果进行拆分
     */
    @SafeVarargs
    public static <T, R> String groupingBy(T t, Function<T, R>... functions) {
        if (functions == null || functions.length == 0) {
            throw new NullPointerException("functions数组不可以为空");
        } else if (functions.length == 1) {
            return functions[0].apply(t).toString();
        } else {
            return Arrays.stream(functions).map(fun -> fun.apply(t).toString()).reduce((str1, str2) -> str1 + "|" + str2).get();
        }
    }
}
